package vn.wallet.app.helper;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import vn.wallet.app.domain.User;
import vn.wallet.app.helper.exceptions.BusinessException;
import vn.wallet.app.helper.exceptions.TechnicalException;

public class AuthorizationFilter implements Filter {

	@Override
	public void destroy() {
		//
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {

		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse res = (HttpServletResponse) response;

		try {
			User user = (User) req.getSession().getAttribute(AppUtils.USER_LOGINED_SESSION_NAME);

			if (user == null) {
				throw new TechnicalException("User not found");
			} else if (!user.isStatus()) {
				throw new BusinessException("Locked user can't access this page");
			} else {
				chain.doFilter(request, response);
			}
		} catch (Exception ex) {
			res.sendRedirect(req.getContextPath() + "/login.htm?message=" + ex.getMessage());
		}
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		//
	}

}
